<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据主题" prop="subjectId">
        <el-select v-model="queryParams.subjectId" placeholder="请选择主题" clearable style="width:120px">
          <el-option
            v-for="dict in subjectOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模型" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入模型名称/代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型层级" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择模型层级" clearable style="width:120px">
          <el-option
            v-for="dict in xdata_model_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width:120px">
          <el-option
            v-for="dict in ext_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dev:model:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dev:model:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Refresh"
            @click="handleRefreshCache"
            v-hasPermi="['dev:model:remove']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据主题" align="center" prop="subjectName" />
      <el-table-column label="模型代码" align="center" prop="code"/>
      <el-table-column label="模型名称" align="center" prop="name" />
      <el-table-column label="主键字段" align="center" prop="pkField" />
      <el-table-column label="唯一标识" align="center" prop="uniqueField" />
      <el-table-column label="模型层级" align="center" prop="level">
        <template #default="scope">
          <dict-tag :options="xdata_model_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="ext_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="模型说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dev:model:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dev:model:remove']">删除</el-button>&nbsp;
          <el-dropdown @command="handleCommand">
            <el-button type="warning" link>
              更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="Operation" :command="'valid_'+scope.row.id">数据验证</el-dropdown-item>
                <el-dropdown-item icon="Grid" :command="'data_'+scope.row.code">数据预览</el-dropdown-item>
                <el-dropdown-item icon="VideoPlay" :command="'preview_'+scope.row.id">功能预览</el-dropdown-item>
                <el-dropdown-item icon="Plus" :command="'menu_'+scope.row.id">添加菜单</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据模型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="modelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据主题" prop="subjectId">
            <el-select v-model="form.subjectId" placeholder="请选择主题" clearable>
            <el-option
              v-for="dict in subjectOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模型代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入模型代码" />
        </el-form-item>
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="主键字段" prop="pkField">
          <el-input v-model="form.pkField" placeholder="请输入主键字段" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="uniqueField">
          <el-input v-model="form.uniqueField" placeholder="请输入唯一标识" />
        </el-form-item>
        <el-form-item label="模型层级" prop="level">
          <el-select v-model="form.level" placeholder="请选择">
            <el-option
              v-for="dict in xdata_model_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in ext_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入模型说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Model">
import { listModel, getModel, delModel, addModel, updateModel, addModelMenu, reloadModel } from "@/api/dev/model";
import { selectSubject } from "@/api/base/subject";

const { proxy } = getCurrentInstance();
const { xdata_model_level, ext_status } = proxy.useDict('xdata_model_level', 'ext_status');

const modelList = ref([]);
const subjectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tab = ref("base");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    subjectId: null,
    code: null,
    name: null,
    type: null,
    status: null,
  },
  rules: {
    subjectId: [
      { required: true, message: "数据主题不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "模型代码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "模型名称不能为空", trigger: "blur" }
    ],
    pkField: [
      { required: true, message: "主键字段不能为空", trigger: "blur" }
    ],
    uniqueField: [
      { required: true, message: "唯一标识不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "业务类型不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询数据模型列表 */
function getList() {
  loading.value = true;
  listModel(queryParams.value).then(response => {
    modelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    subjectId: null,
    code: null,
    name: null,
    pkField: null,
    uniqueField: null,
    type: null,
    status: null,
    querySql: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("modelRef");
  tab.value = 'base';
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加数据模型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getModel(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改数据模型";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["modelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateModel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addModel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除数据模型编号为"' + _ids + '"的数据项？').then(function() {
    return delModel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dev/model/export', {
    ...queryParams.value
  }, `model_${new Date().getTime()}.xlsx`)
}

/** 下拉按钮菜单事件 */
function handleCommand(command){
  let pos = command.indexOf('_');
  let cmd = command.substring(0,pos);
  let p = command.substring(pos+1);
  if(cmd == 'field'){
    //进入字段配置
    proxy.$tab.openPage('/dev/model/field/'+p);
  }else if(cmd == 'event'){
    //进入事件配置
    proxy.$tab.openPage('/dev/model/event/'+p);
  }else if(cmd == 'data'){
    //进入数据预览
    proxy.$tab.openPage('/dev/model/data/'+p);
  }else if(cmd == 'preview'){
    console.log('goto: /dev/preview/'+p);
    //进入功能预览
    proxy.$tab.openPage('/dev/preview/'+p);
  }else if(cmd == 'menu'){
    proxy.$modal.confirm('是否确认将当前数据模型功能添加到菜单？').then(function() {
      return addModelMenu(p);
    }).then(() => {
      proxy.$modal.msgSuccess("添加成功");
    }).catch(() => {});
  }else{
    proxy.$modal.msgError("不支持的操作");
  }  
}

/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  reloadModel().then(() => {
    proxy.$modal.msgSuccess("刷新成功");
  });
}

getList();

selectSubject().then(response => {
    subjectOptions.value = response.rows;
});
</script>
